package Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2023-02-25
 * Time: 22:08
 */
class MyBlockingQueue{
    private int[] items = new int[1000];
    private int head = 0;
    private int tail = 0;
    private int size = 0;
//    入队列
    public void put(int value) throws InterruptedException {
        synchronized (this) {
            while (size == items.length){
                //队列满了,此时要产生阻塞
                this.wait();
            }
            items[tail] = value;
            tail++;
            //tail的处理
            //tail = tail % items.length;
            if(tail >= items.length){
                tail = 0;
            }
            size++;
//            这个notify唤醒take中的wait
            this.notify();
        }

    }
    //出队列
    public Integer take() throws InterruptedException {
        int result = 0;
        synchronized (this) {
            while (size == 0){
                //队列空,也应该阻塞
                this.wait();
            }
            result = items[head];
            head++;
            if(head >= items.length){
                head = 0;
            }
            size--;
            //唤醒put中的wait
            this.notify();
        }
        return result;
    }

}

public class Thread24 {
    public static void main(String[] args) throws InterruptedException {
//        MyBlockingQueue queue = new MyBlockingQueue();
//        queue.put(1);
//        queue.put(2);
//        queue.put(3);
//        queue.put(4);
//        int result = 0;
//        result = queue.take();
//        System.out.println("result = " + result);
//        result = queue.take();
//        System.out.println("result = " + result);
//        result = queue.take();
//        System.out.println("result = " + result);
//        result = queue.take();
//        System.out.println("result = " + result);
       /* result = queue.take();
        System.out.println("result = " + result);*/
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread customer = new Thread(() ->{

            while (true) {
                try {
                    int result = queue.take();
                    System.out.println("消费 :" + result);
//                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        customer.start();
        Thread producer = new Thread(()->{
            int count = 0;
            while (true) {
                try {
                    Thread.sleep(500);
                    System.out.println("生产: "+ count);
                    queue.put(count);
                    count++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        producer.start();
    }
}
